package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/proxy"
	"k8s.io/client-go/rest"
)

/** Gin + Client go 开发示例 */
// func test() {
// 	fmt.Println("start...")
// 	stopCh := make(chan struct{})
// 	err := NewShareInformerFactory(stopCh)
// 	if err != nil {
// 		panic(err)
// 	}
// 	items, err := Get().Core().V1().Pods().Lister().List(labels.Everything())
// 	if err != nil {
// 		panic(err)
// 	}

// 	for _, v := range items {
// 		fmt.Printf("ns: %v, names: %v \n", v.Namespace, v.Name)
// 	}
// }

func main() {
	fmt.Println("start...")

	// 实即化informer
	err := Setup()
	if err != nil {
		panic(err)
	}

	// 启动web服务
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code":    20000,
			"message": "pong",
		})
	})

	r.GET("/pod/list", func(c *gin.Context) {
		items, err := Get().Core().V1().Pods().Lister().List(labels.Everything())
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    40000,
				"message": err.Error(),
			})
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    20000,
			"message": "sucess",
			"data":    items,
		})
	})

	r.GET("/:resource/:group/:version", func(c *gin.Context) {
		resource := c.Param("resource")
		group := c.Param("group")
		version := c.Param("version")
		gvr := schema.GroupVersionResource{
			Group:    group,
			Version:  version,
			Resource: resource,
		}

		i, err := Get().ForResource(gvr)
		if err != nil {
			panic(err.Error())
		}
		items, err := i.Lister().List(labels.Everything())
		if err != nil {
			panic(err.Error())
		}
		c.JSON(http.StatusOK, gin.H{
			"code":    20000,
			"message": "sucess",
			"data":    items,
		})
	})

	r.Any("/apis/*action", func(c *gin.Context) {

		t, err := rest.TransportFor(clients.GetConfig())
		if err != nil {
			panic(err)
		}

		s := *c.Request.URL
		s.Host = "192.168.39.191:8443"
		s.Scheme = "https"
		httpProxy := proxy.NewUpgradeAwareHandler(&s, t, true, false, nil)
		httpProxy.UpgradeTransport = proxy.NewUpgradeRequestRoundTripper(t, t)
		httpProxy.ServeHTTP(c.Writer, c.Request)
	})
	_ = r.Run(":8888")

}
